package start

import (
	"github.com/gorilla/mux"
	"log"
	"net/http"
	"src/config"
	"src/service"
)

// http 路由逻辑
type Router struct {
	GroupName string
	Path      string
	Params    map[string]any
	OnBefore  []func(*service.Req)
	Run       func(*service.Req)
	OnAfter   []func(*service.Req)
	Req       *service.Req
}
type RouterGroup struct {
	Path     string
	Name     string
	Routers  []*Router
	Params   map[string]any
	OnBefore []func(*service.Req)
	Run      func(*service.Req)
	OnAfter  []func(*service.Req)
	Req      *service.Req
}

func (this *RouterGroup) Add(router *Router) *RouterGroup {
	this.Routers = append(this.Routers, router)
	return this
}
func (this *RouterGroup) Reg(http *mux.Router) *RouterGroup {
	for _, router := range this.Routers {
		router.GroupName = this.Name
		router.Path = this.Path + router.Path
		if router.Run == nil && this.Run != nil {
			router.Run = this.Run
		}
		if router.OnBefore == nil && this.OnBefore != nil {
			router.OnBefore = this.OnBefore
		}
		if router.OnAfter == nil && this.OnAfter != nil {
			router.OnAfter = this.OnAfter
		}
		if router.Req == nil && this.Req != nil {
			router.Req = this.Req
		}
		router.Reg(http)
	}
	return this
}

// 注册路由
func (this *Router) Reg(http1 *mux.Router) {
	contextPath := config.V().GetString("server.http.servlet.context-path")
	http1.HandleFunc(contextPath+this.Path, func(w http.ResponseWriter, r *http.Request) {
		defer log.Println("请求结束")
		//defer func() {
		//	log.Println("start.Reg 退出")
		//}()
		serverStop := config.V().GetBool("server-close.close")
		if serverStop {
			log.Println("服务器关闭中，当前请求被拦截 start.Reg")
			return
		}
		req := service.New(w, r)
		req.RouterParams = this.Params
		req.RouterPath = this.Path

		if this.OnBefore != nil {
			//log.Println("正在执行方法 start.OnBefore")
			for _, runBefore := range this.OnBefore {
				req.Next(runBefore)
			}
		}
		if this.Run != nil {
			//log.Println("正在执行方法 start.Run")
			req.Next(this.Run)
		}

		if this.OnAfter != nil {
			//req.Close = false
			//log.Println("正在执行方法 start.OnAfter")
			for _, runAfter := range this.OnAfter {
				req.Next(runAfter)
			}
		}
		log.Println("新的http请求进入 正在执行方法 start.Reg------------")

	})
}
